#include"apue.h"
//清屏
void clears(void)
{
	system("clear");
}
//清理输入缓冲区
void clear_stdin(void)
{
	stdin->_IO_read_ptr=stdin->_IO_read_end;
}
//获取字符串
char* get_str(char* str,int size)
{
	clear_stdin();

	fgets(str,size,stdin);

	int len=strlen(str);
	if(str[len-1]=='\n')
	{
		str[len-1]='\0';
	}
	clear_stdin();
}
//获取指令
char get_cmd(char start,char end)
{
	clear_stdin();
	printf("请输入指令：");
	while(1)
	{
		char val=get_keyboard();
		if(val>=start&&val<=end)
		{
			printf("%c\n",val);
			return val;
		}
	}
}
//获取密码
char* get_pwd(char* pd,int size)
{
	clear_stdin();

	int index=0;
	while(index<size-1)
	{
		char val=get_keyboard();
		if(KEY_ENTER==val) break;

		if(KEY_BACKSPACE==val)
		{
			if(0>=index) continue;
			printf("\b \b");
			index--;
		}
		pd[index++]=val;
		printf("*");
	}

	clear_stdin();
	pd[index]='\0';
	printf("\n");
	return pd;
}

//初始化id
int init_id(const char* path,int id)
{
	if(0==access(path,F_OK))
	{
		return 0;
	}
	int fd=open(path,O_WRONLY|O_CREAT|O_TRUNC,0644);
	if(-1==fd)
	{
		perror("open");
		return -1;
	}
	if(0>=write(fd,&id,sizeof(id)))
	{
		perror("error");
		return -1;
	}
	close(fd);
	return 0;
}

//获取ID
int get_id(const char* path)
{
	int id=0;
	int fd=open(path,O_RDWR);
	if(-1==fd)
	{
		perror("open");
		return -1;
	}
	if(0>=read(fd,&id,sizeof(id)))
	{
		perror("read");
		return -1;
	}
	id++;
	lseek(fd,SEEK_SET,0);
	if(0>=write(fd,&id,sizeof(id)))
	{
		perror("write");
		return -1;
	}
	close(fd);
	return id-1;
}

//输入任意建继续
void anykey_continue(void)
{
	printf("请按任意建继续...");
	get_keyboard();
	printf("\n");
}

//显示提示信息
void show_msg(char* msg,float sec)
{
	printf("\33[;34m");
	printf("***%s***\n",msg);
	usleep(sec*1000000);
	printf("\33[0m");
}
